<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.css" rel="stylesheet" />
		<link rel="stylesheet" href="../css/icons.css">
		<link rel="stylesheet" href="../css/chat.css">
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<h1 class="mui-title">棚博士智能问答</h1>
		</header>
		<!-- 聊天内容区域 -->
		<div class="chat-container">
		</div>

		<!-- 底部输入区域 -->
		<div class="input-area">
			<div class="input-container">
				<!-- 图片功能按钮 -->
				<div class="image-actions">
					<button class="image-button" id="camera-btn" title="拍照识别">
						<i class="mui-icon mui-icon-camera" style="font-size: 20px; color: #2E7D32;"></i>
					</button>
					<button class="image-button" id="gallery-btn" title="选择图片">
						<i class="mui-icon mui-icon-image" style="font-size: 20px; color: #2E7D32;"></i>
					</button>
				</div>
				
				<div class="input-field">
					<input type="text" placeholder="请输入您的农业相关问题...">
				</div>
				<button class="send-button" style="display: ;">
					<i class="icon icon-paper-plane"
						style="width: 20px; height: 20px; display: flex; justify-content: center; align-items: center;"></i>
				</button>
				<button class="stop-button" style="display: none;">
					<span class="mui-icon mui-icon-close"
						style="width: 20px; height: 20px; display: flex; justify-content: center; align-items: center;"></span>
				</button>
			</div>
		</div>

		<!-- 图片预览模态框 -->
		<div id="image-preview-modal" class="modal" style="display: none;">
			<div class="modal-content">
				<div class="modal-header">
					<h3>图片预览</h3>
					<button class="close-btn" id="close-preview">&times;</button>
				</div>
				<div class="modal-body" style="display: flex; flex-direction: column; align-items: center;">
					<img id="preview-image" src="" alt="预览图片" style="max-width: 100%; max-height: 300px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.08);">
					<input id="image-question" type="text" placeholder="请输入你想问的问题"
						style="width: 90%; margin-top: 18px; margin-bottom: 8px; padding: 10px 14px; border-radius: 6px; border: 1px solid #e0e0e0; font-size: 16px; box-sizing: border-box; outline: none;"/>
				</div>
				<div class="modal-footer" style="display: flex; justify-content: flex-end; gap: 16px; padding: 0 16px 8px 16px;">
					<button class="btn btn-secondary" id="cancel-image"
						style="min-width: 90px; height: 38px; border-radius: 6px; border: none; background: #f5f5f5; color: #666; font-size: 15px;">取消</button>
					<button class="btn btn-primary" id="send-image"
						style="min-width: 110px; height: 38px; border-radius: 6px; border: none; background: #2E7D32; color: #fff; font-size: 15px; font-weight: 500;">发送图片</button>
				</div>
			</div>
		</div>

		<script src="../js/mui.js"></script>
		<script src="../js/request.js"></script>
		<script src="../js/storage.js"></script>
		<script src="../js/imageRecognition.js"></script>
		<script>
			var imageRecognition = new ImageRecognition();
			let user = userCache.getUser();
			let userId = user.userId;
			let assistantMsgIndex = 0;
			let baseUrl = localStorage.getItem("ip");
			let eventSource = null;
			let currentImageData = null;

			mui.init()

			window.addEventListener('refresh', function(event) {
				refresh()
			});

			// 发送按钮点击事件
			document.querySelector('.send-button').addEventListener('click', function() {
				const input = document.querySelector('input');
				const message = input.value.trim();
				if (message === '') {
					mui.toast('请输入您的问题');
					return;
				}
				document.querySelector('.send-button').style.display = 'none';
				document.querySelector('.stop-button').style.display = '';
				sendMessage();
			});

			document.querySelector('.stop-button').addEventListener('click', function() {
				if (eventSource) {
					eventSource.close();
				}
				// 移除打字指示器
				const typingIndicators = document.querySelectorAll('.typing-indicator');
				if (typingIndicators[typingIndicators.length - 1]) {
					typingIndicators[typingIndicators.length - 1].style.display = 'none';
					document.querySelector('.send-button').disabled = false;
				}
				document.querySelector('.send-button').style.display = '';
				document.querySelector('.stop-button').style.display = 'none';
			});

			function refresh() {
				if (eventSource) {
					eventSource.close();
				}
				assistantMsgIndex = 0;
				const chatContainer = document.querySelector('.chat-container');
				const height = window.innerHeight;
				chatContainer.style.height = `${height - 100}px`;
				chatContainer.innerHTML = '';
				document.querySelector('.send-button').style.display = '';
				document.querySelector('.stop-button').style.display = 'none';
				getHistoryMsg();
			}

			refresh()

			//获取最新的20条历史消息
			function getHistoryMsg() {
				let params = {
					"userId": userId,
					"pageNum": 1,
					"pageSize": 20,
					"orderByColumn": "create_time",
					"isAsc": "desc",
				}
				request.get('/system/chatMessages/list', params, (resp) => {
					console.log('获取历史消息成功')
					let list = resp.rows;
					list = list.reverse();
					for (let i = 0; i < list.length; i++) {
						assistantMsgIndex++;
						if (list[i].imageData) {
							addImageMessage(list[i].role, list[i].imageData);
						} else {
							addMessage(list[i].role, list[i].content, true);
						}
					}
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端历史聊天记录失败', error)
				})
			}

			// 发送消息
			function sendMessage() {
				const input = document.querySelector('input');
				const message = input.value.trim();
				if (!message) return;

				// 添加用户消息到界面
				addMessage('user', message);
				input.value = '';

				// 保存聊天记录
				let data = {
					userId: userId, 
					content: message,
					role: 'user',
				}
				request.post("/system/chatMessages", data, (resp) => {
					console.log('调用服务端保存聊天记录成功')
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端保存聊天记录失败', error)
				})

				assistantMsgIndex++;
				addMessage('assistant', '');

				// 新AI对话流式接口
				let aiReply = '';
				imageRecognition.sendChatToAIStream(
					message,
					userId,
					(data) => {
						console.log('[AI流式] onMessage收到:', data);
						aiReply += data;
						console.log('[AI流式] 拼接后内容:', aiReply);
						updateLastAssistantMessage(aiReply);
					},
					(error) => {
						mui.toast('AI对话失败: ' + error);
						document.querySelector('.send-button').style.display = '';
						document.querySelector('.stop-button').style.display = 'none';
					}
				);
			}

			// 新增：结束打字状态
			function finishAssistantMessage() {
				document.querySelector('.send-button').style.display = '';
				document.querySelector('.stop-button').style.display = 'none';
			}
			window.finishAssistantMessage = finishAssistantMessage;

			// 新增：更新最后一条AI消息内容
			function updateLastAssistantMessage(content) {
				const chatContainer = document.querySelector('.chat-container');
				const assistantMessages = chatContainer.querySelectorAll('.message-container .assistant-message');
				if (assistantMessages.length > 0) {
					console.log('[AI流式] updateLastAssistantMessage渲染:', content);
					assistantMessages[assistantMessages.length - 1].innerHTML = `<p>${content}</p>`;
				}
			}

			function addMessage(role, message, history = false) {
				// 创建用户消息元素
				const chatContainer = document.querySelector('.chat-container');
				if (role === 'user') {
					const input = document.querySelector('input');
					const userMessage = document.createElement('div');
					userMessage.className = 'message-container user';
					userMessage.innerHTML = `
					        <div class="chat-bubble user-message">
					            <p>${message}</p>
					        </div>
					        <div class="message-avatar user-avatar">
					            <i class="icon icon-user avatar-icon"></i>
					        </div>
					    `;

					chatContainer.appendChild(userMessage);
					input.value = '';

					// 滚动到底部
					chatContainer.scrollTop = chatContainer.scrollHeight;
				}
				if (role === 'assistant') {
					let newTypingMessage = document.getElementById('new-typing-message-' + assistantMsgIndex);
					if (!newTypingMessage) {
						const typingDiv = document.createElement('div');
						typingDiv.className = 'message-container';
						if (!history) {
							typingDiv.innerHTML = `
							                        <div class="message-avatar assistant-avatar">
							                            <i class="icon icon-leaf avatar-icon"></i>
							                        </div>
							                        <div class="chat-bubble assistant-message">
							                            <p id="new-typing-message-${assistantMsgIndex}"></p>
							                            <div class="typing-indicator mt-2">
							                                <span></span>
							                                <span></span>
							                                <span></span>
							                            </div>
							                        </div>
							                    `;
						} else {
							typingDiv.innerHTML = `
							                        <div class="message-avatar assistant-avatar">
							                            <i class="icon icon-leaf avatar-icon"></i>
							                        </div>
							                        <div class="chat-bubble assistant-message">
							                            <p id="new-typing-message-${assistantMsgIndex}"></p>
							                        </div>
							                    `;
						}
						chatContainer.appendChild(typingDiv);
						if (history) {
							newTypingMessage = document.getElementById('new-typing-message-' + assistantMsgIndex);
							newTypingMessage.innerHTML = message;
						}
						chatContainer.scrollTop = chatContainer.scrollHeight;
					} else {
						if (message) {
							if (!message.toUpperCase().includes('<EOF>')) { //输出未结束
								newTypingMessage.innerHTML = message;
								chatContainer.scrollTop = chatContainer.scrollHeight;
							} else {
								if (!history) {
									// 移除打字指示器
									const typingIndicators = document.querySelectorAll('.typing-indicator');
									if (typingIndicators[typingIndicators.length - 1]) {
										typingIndicators[typingIndicators.length - 1].style.display = 'none';
										document.querySelector('.send-button').disabled = false;
									}
								}
							}
						}
					}
				}
			}

			// 获取当前时间
			function getCurrentTime() {
				const now = new Date();
				const hours = now.getHours().toString().padStart(2, '0');
				const minutes = now.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			}

			// 输入框回车键发送
			document.querySelector('input').addEventListener('keypress', function(e) {
				if (e.key === 'Enter') {
					document.querySelector('.send-button').click();
				}
			});

			// ===== 全新图片识别流程开始 =====
			// 按钮和预览区请确保页面有如下结构：
			// <button id="camera-btn">拍照</button>
			// <button id="gallery-btn">相册</button>
			// <div id="image-preview-modal" style="display:none;">
			//   <img id="preview-image" style="max-width: 200px; max-height: 200px;">
			//   <button id="send-image">发送</button>
			//   <button id="cancel-image">取消</button>
			// </div>

			// 拍照
			if (document.getElementById('camera-btn')) {
			    document.getElementById('camera-btn').addEventListener('click', function() {
			        plus.camera.getCamera().captureImage(function(path) {
			            plus.io.resolveLocalFileSystemURL(path, function(entry) {
			                showImagePreview(entry.toLocalURL());
			            }, function() {
			                mui.toast('图片路径获取失败');
			            });
			        }, function(e) {
			            mui.toast('拍照失败');
			        });
			    });
			}

			// 相册
			if (document.getElementById('gallery-btn')) {
			    document.getElementById('gallery-btn').addEventListener('click', function() {
			        plus.gallery.pick(function(path) {
			            showImagePreview(path);
			        }, function(e) {
			            mui.toast('未选择图片');
			        });
			    });
			}

			// ===== 终极兼容 DCloud/H5 的图片预览与发送 =====
			function showImagePreview(file) {
			    const modal = document.getElementById('image-preview-modal');
			    const previewImage = document.getElementById('preview-image');
			    if (typeof file === 'string' && file.startsWith('file://')) {
			        previewImage.src = file;
			    } else if ((typeof File !== 'undefined' && file instanceof File) || (typeof Blob !== 'undefined' && file instanceof Blob)) {
			        var reader = new FileReader();
			        reader.onload = function(e) {
			            previewImage.src = e.target.result;
			        };
			        reader.readAsDataURL(file);
			    } else {
			        mui.toast('图片预览失败，文件类型不支持');
			        return;
			    }
			    window.currentImageFile = file;
			    modal.style.display = 'block';
			}

			// 取消预览
			if (document.getElementById('cancel-image')) {
			    document.getElementById('cancel-image').addEventListener('click', function() {
			        document.getElementById('image-preview-modal').style.display = 'none';
			        window.currentImageFile = null;
			    });
			}

			// 发送图片
			if (document.getElementById('send-image')) {
			    document.getElementById('send-image').addEventListener('click', function() {
			        if (!window.currentImageFile) {
			            mui.toast('请先选择图片');
			            return;
			        }
			        // 获取输入框内容
			        var question = document.getElementById('image-question').value.trim();
			        if (!question) question = '请描述这张图片';
			        sendImageMessage(window.currentImageFile, question);
			        document.getElementById('image-preview-modal').style.display = 'none';
			        window.currentImageFile = null;
			    });
			}

			// 发送图片核心逻辑
			function sendImageMessage(file, question) {
				if (typeof file === 'string' && file.startsWith('file://')) {
					// DCloud环境，先预览用本地路径，再传fileObj
					plus.io.resolveLocalFileSystemURL(file, function(entry) {
						addImageMessage('user', entry.toLocalURL());
						entry.file(function(fileObj) {
							// DCloud fileObj转Blob
							var reader = new plus.io.FileReader();
							reader.onloadend = function(e) {
								var arr = e.target.result.split(',');
								var mime = arr[0].match(/:(.*?);/)[1];
								var bstr = atob(arr[1]);
								var n = bstr.length;
								var u8arr = new Uint8Array(n);
								while(n--){
									u8arr[n] = bstr.charCodeAt(n);
								}
								var blob = new Blob([u8arr], {type: mime});
								sendImageToAI(blob, question);
							};
							reader.readAsDataURL(fileObj);
						}, function(e) {
							mui.toast('读取图片文件失败');
						});
					});
				} else if ((typeof File !== 'undefined' && file instanceof File) || (typeof Blob !== 'undefined' && file instanceof Blob)) {
					addImageMessage('user', URL.createObjectURL(file));
					sendImageToAI(file, question);
				} else {
					mui.toast('图片发送失败，文件类型不支持');
					return;
				}
			}

			// 展示图片消息
			function addImageMessage(role, imageData) {
			    const chatContainer = document.querySelector('.chat-container');
			    if (role === 'user') {
			        const userMessage = document.createElement('div');
			        userMessage.className = 'message-container user';
			        userMessage.innerHTML = `
			            <div class="chat-bubble user-message">
			                <img src="${imageData}" alt="用户图片" style="max-width: 200px; max-height: 200px; border-radius: 8px;">
			            </div>
			            <div class="message-avatar user-avatar">
			                <i class="icon icon-user avatar-icon"></i>
			            </div>
			        `;
			        chatContainer.appendChild(userMessage);
			        chatContainer.scrollTop = chatContainer.scrollHeight;
			    }
			}

			// 发送给智谱AI图片识别API（前端直连）
			function sendImageToAI(file, question) {
			    assistantMsgIndex++;
			    addMessage('assistant', '');

			    // 读取图片为base64
			    const reader = new FileReader();
			    reader.onload = function(e) {
			        const base64 = e.target.result.split(',')[1];
			        const apiKey = '2a9011e89d9d4b8585a59725a203a432.umEXjloqQjF7kyQK';
			        const body = {
			            model: 'glm-4v-plus-0111',
			            messages: [
			                {
			                    role: 'user',
			                    content: [
			                        {
			                            type: 'image_url',
			                            image_url: { url: 'data:image/jpeg;base64,' + base64 }
			                        },
			                        {
			                            type: 'text',
			                            text: question
			                        }
			                    ]
			                }
			            ]
			        };
			        // 这里用 fetch 发送请求（假设是这样实现的）
			        fetch('https://open.bigmodel.cn/api/paas/v4/chat/completions', {
			            method: 'POST',
			            headers: {
			                'Content-Type': 'application/json',
			                'Authorization': 'Bearer ' + apiKey
			            },
			            body: JSON.stringify(body)
			        })
			        .then(res => res.json())
			        .then(data => {
			            // 渲染 assistant 消息内容
			            let result = '';
			            if (data && data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content) {
			                result = data.choices[0].message.content;
			            } else {
			                result = '图片识别失败';
			            }
			            addMessage('assistant', result);
			            // --- 关键补丁：隐藏打字指示器 ---
			            const typingIndicators = document.querySelectorAll('.typing-indicator');
			            if (typingIndicators.length > 0) {
			                typingIndicators[typingIndicators.length - 1].style.display = 'none';
			            }
			        })
			        .catch(err => {
			            addMessage('assistant', '图片识别出错');
			            // --- 关键补丁：隐藏打字指示器 ---
			            const typingIndicators = document.querySelectorAll('.typing-indicator');
			            if (typingIndicators.length > 0) {
			                typingIndicators[typingIndicators.length - 1].style.display = 'none';
			            }
			        });
			    };
			    reader.readAsDataURL(file);
			}
			// ===== 全新图片识别流程结束 =====
		</script>
	</body>

</html>